<?php

class WPFB_AdminGuiFiles {

    static $FilesPerPage = 50;

    static function Display() {
        global $wpdb, $user_ID;

        wpfb_loadclass('File', 'Category', 'Admin', 'Output');

        $_POST = stripslashes_deep($_POST);
        $_GET = stripslashes_deep($_GET);

        $action = !empty($_REQUEST['action']) ? $_REQUEST['action'] : '';
        $clean_uri = remove_query_arg(array('message', 'action', 'file_id', 'cat_id', 'deltpl', 'hash_sync' /* , 's' */)); // keep search keyword
        // nonce/referer check (security)
        if ($action == 'updatefile' || $action == 'addfile') {
            $nonce_action = WPFB . "-" . $action;
            if ($action == 'updatefile')
                $nonce_action .= $_POST['file_id'];
            if (!wp_verify_nonce($_POST['wpfb-file-nonce'], $nonce_action) || !check_admin_referer($nonce_action, 'wpfb-file-nonce'))
                wp_die(__('Cheatin&#8217; uh?'));
        }

        // switch simple/extended form
        if (isset($_GET['exform'])) {
            $exform = (!empty($_GET['exform']) && $_GET['exform'] == 1);
            update_user_option($user_ID, WPFB_OPT_NAME . '_exform', $exform);
        } else
            $exform = (bool) get_user_option(WPFB_OPT_NAME . '_exform');

        if (!empty($_REQUEST['redirect']) && !empty($_REQUEST['redirect_to']))
            WPFB_AdminLite::JsRedirect($_REQUEST['redirect_to']);
        ?>
        <div class="wrap">
            <?php
            switch ($action) {
                case 'editfile':
                    if (!current_user_can('upload_files'))
                        wp_die(__('Cheatin&#8217; uh?'));

                    if (!empty($_POST['files'])) {
                        if (!is_array($_POST['files']))
                            $_POST['files'] = explode(',', $_POST['files']);
                        $files = array();
                        foreach ($_POST['files'] as $file_id) {
                            $file = WPFB_File::GetFile($file_id);
                            if (!is_null($file) && $file->CurUserCanEdit())
                                $files[] = $file;
                        }
                        if (count($files) > 0)
                            WPFB_Admin::PrintForm('file', $files, array('multi_edit' => true));
                        else
                            wp_die('No files to edit.');
                    } else {
                        $file = WPFB_File::GetFile($_GET['file_id']);
                    //    if (is_null($file) || !$file->CurUserCanEdit())
                        if (is_null($file))
                            wp_die(__('You do not have the permission to edit this file!', WPFB));
                        WPFB_Admin::PrintForm('file', $file);
                    }
                    break;

                case 'updatefile':
                    $file_id = (int) $_POST['file_id'];
                    $update = true;
                    $file = WPFB_File::GetFile($file_id);
                    self::AssignFileToUsers($file, $_POST['user_file']);
                  // if (is_null($file) || !$file->CurUserCanEdit())
                    if (is_null($file))
                        wp_die(__('Cheatin&#8217; uh?'));


                case 'addfile':
                    $update = !empty($update);

                    if (!WPFB_Admin::CurUserCanUpload())
                        wp_die(__('Cheatin&#8217; uh?'));

                    extract($_POST);
                    if (isset($jj) && isset($ss)) {
                        $jj = ($jj > 31 ) ? 31 : $jj;
                        $hh = ($hh > 23 ) ? $hh - 24 : $hh;
                        $mn = ($mn > 59 ) ? $mn - 60 : $mn;
                        $ss = ($ss > 59 ) ? $ss - 60 : $ss;
                        $_POST['file_date'] = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss);
                    }

                    $result = WPFB_Admin::InsertFile(array_merge($_POST, $_FILES), true);
                    if (isset($result['error']) && $result['error']) {
                        $message = $result['error'] . '<br /><a href="javascript:history.back()">' . __("Go back") . '</a>';
                    } else {
                        $message = $update ? __('File updated.', WPFB) : __('File added.', WPFB);
                    }

                default:
                    if (!current_user_can('upload_files'))
                        wp_die(__('Cheatin&#8217; uh?'));


                    if (!empty($_POST['deleteit'])) {
                        foreach ((array) $_POST['delete'] as $file_id) {
                            if (is_object($file = WPFB_File::GetFile($file_id)))
                                $file->Remove(true);
                        }
                        WPFB_File::UpdateTags();
                    }
                    ?>
                    <h2><?php
                        echo str_replace(array('(<', '>)'), array('<', '>'), sprintf(__('Manage Files (<a href="%s">add new</a>)', WPFB), '#addfile" class="add-new-h2'));
                        echo '<a href="' . admin_url('admin.php?page=wpfilebase_manage&amp;action=batch-upload') . '" class="add-new-h2">' . __('Batch Upload', WPFB) . '</a>';

                        if (isset($_GET['s']) && $_GET['s'])
                            printf('<span class="subtitle">' . __('Search results for &#8220;%s&#8221;'/* def */) . '</span>', esc_html(stripslashes($_GET['s'])));
                        ?></h2>
                    <?php if (!empty($message)) : ?><div id="message" class="updated fade"><p><?php echo $message; ?></p></div><?php
                    endif;
                    if (WPFB_Admin::CurUserCanUpload() && ($action == 'addfile' || $action == 'updatefile')) {
                        unset($file);
                        WPFB_Admin::PrintForm('file', null, array('exform' => $exform, 'item' => new WPFB_File((isset($result['error']) && $result['error']) ? $_POST : null)));
                    }
                    wpfb_loadclass('FileListTable');
                    $file_table = new WPFB_FileListTable();
                    $file_table->prepare_items();
                    ?>

                    <form class="search-form topmargin" action="" method="get">
                        <input type="hidden" value="<?php echo esc_attr($_GET['page']); ?>" name="page" />
                        <input type="hidden" value="<?php echo empty($_GET['view']) ? '' : esc_attr(@$_GET['view']); ?>" name="view" />
                        <?php $file_table->search_box(__("Search Files", WPFB), 's'); ?>
                    </form>	

                    <?php $file_table->views(); ?>
                    <form id="posts-filter" action="" method="post">
                        <input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>" />
                        <?php $file_table->display() ?>
                    </form>
                    <br class="clear" />

                    <?php
                    if ($action != 'addfile' && $action != 'updatefile' && WPFB_Admin::CurUserCanUpload()) {

                        unset($file);
                        WPFB_Admin::PrintForm('file', null, array('exform' => $exform));
                    }
                    break; // default
            }
            ?>




        </div> <!-- wrap -->
        <?php
    }

    static function PrintFileInfo($info, $path = 'file_info') {
        foreach ($info as $key => $val) {
            $p = $path . '/' . $key;
            if (is_array($val) && count($val) == 1 && isset($val[0])) // if its a single array, just take the first element
                $val = $val[0];
            echo '<b>', esc_html($p), "</b> = ", esc_html($val), "\n";
            if (is_array($val) || is_object($val)) {
                self::PrintFileInfo($val, $p);
            }
        }
    }

    static function AssignFileToUsers($file, $users) {
        GLOBAL $wpdb;
        //Delete old assigned files to selected users
        $wpdb->query($wpdb->prepare(" DELETE FROM wp_wpfb_user_files WHERE file = " . $file->file_id));
        //Assigned files to users
        foreach ($users as $files) {
            foreach ($files as $user_id =>$val) {         
                $wpdb->query($wpdb->prepare("INSERT INTO wp_wpfb_user_files(user, file ) VALUES (".$user_id.",".$file->file_id.")"));
            }
        }
    }

    static function FileInfoPathsBox($info) {
        ?><p><?php printf(__('The following tags can be used in templates. For example, if you want to display the Artist of a MP3 File, put %s inside the template code.', WPFB), '<code>%file_info/tags/id3v2/artist%</code>'); ?></p>
        <pre>
        <?php self::PrintFileInfo(empty($info->value) ? $info : $info->value); ?>
        </pre>	
        <?php
        if (!empty($info->keywords)) {
            ?><p><b><?php _e('Keywords used for search:', WPFB) ?></b> <?php echo esc_html($info->keywords) ?></p> <?php
        }
    }

    static function dump($var) {
        ob_start();
        var_dump($var);
        $output = ob_get_clean();

        $outputFile = "E:/test/dump.txt";
        $filehandle = fopen($outputFile, 'w') or die('File creation error.');
        fwrite($filehandle, $output);
        fclose($filehandle);
    }

}
